package com.axend.aerosense.dev.viewmodel;

import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.dev.entity.RadarInfoBean;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.dev.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * @author ChenHongWei
 * @date :2021/1/19 10:04
 */

public class FamilyWifiViewModel extends CustomBaseViewModel<RadarNetworkBean> {

    /**
     * 当前页面的状态
     * 0：正常，选择wifi、输入密码界面
     * 1：重新搜索wifi的界面
     * 2：连接中，正在连接界面，界面显示等待界面
     * 3：设备联网失败的界面
     */
    public MutableLiveData<Integer> pageState = new MutableLiveData<>(0);
    //雷达联网成功
    public MutableLiveData<Boolean> isRadarConnectNetSuccess = new MutableLiveData<>(false);

    public String radarId;
    public String radarVersion = "00.00.00.00";

    // 雷达类型
    public RadarType radarType;

    //当前总计等待时间
    private int timeCount;
    //停止时间（秒）
    private int stopTime = 120;
    //间隔时间（秒）
    private int interval = 5;
    private Disposable statusDisposable;
    private Disposable httpDisposable;

    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;

    private boolean isStop = false;

    public FamilyWifiViewModel(IBaseView baseViewImpl, ILoadDataResult<RadarNetworkBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        ARouter.getInstance().inject(this);
    }

    //设置页面状态
    public void setPageState(Integer state) {
        pageState.setValue(state);
    }

    //按照指定间隔发送请求到服务器获取雷达的联网状态
    public void getRadarStatus(){
        statusDisposable = Observable.interval(interval, TimeUnit.SECONDS)
                .takeWhile(new Predicate<Long>() {
                    @Override
                    public boolean test(@Nullable Long aLong) throws Exception {
                        return !isStop;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //等待超时
                        timeCount += interval;
                        if (timeCount >= stopTime){
                            ToastUtils.showLong(R.string.dev_device_connect_network_failed);
                            isStop = true;
                            statusDisposable.dispose();
                            setPageState(3);
                        }
                        getRadarNetWorkStatus();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        if (statusDisposable != null){
                            isStop = true;
                            statusDisposable.dispose();
                        }
                        setPageState(3);
                    }
                });
    }

    private void setRadarInfo(){
        if (null != radarId && null != radarVersion){
            String radarName = radarId.substring(radarId.length() - 5);
            RadarInfoBean radarInfoBean = new RadarInfoBean(
                    radarId,
                    radarName,
                    radarVersion,
                    radarType.getNameByString(),
                    radarType.get());
            httpDisposable = EasyHttp.post(UrlApi.URL.SetRadarInfo.getUrl())
                    .cacheMode(CacheMode.NO_CACHE)
                    .headers("token", iLoginService.getToken())
                    .upJson(JsonUtil.toJson(radarInfoBean))
                    .execute(new SimpleCallBack<BaseStringBean>() {
                        @Override
                        public void onTokenExpire() {
                            ToastUtils.showShort(R.string.common_login_first);
                            ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                        }

                        @Override
                        public void onError(ApiException e) {
                            e.printStackTrace();
                            if (e.getCode() == 101){
                                ToastUtils.showLong(R.string.dev_device_re_bind);
                                LiveDatabus.getInstance().with(Gobal.EVENT_KEY.DEV_COUNT_CHANGE,Integer.class).postValue(1);
                                setPageState(0);
                                isRadarConnectNetSuccess.setValue(true);
                            }
                            pageState.setValue(3);
                        }

                        @Override
                        public void onSuccess(BaseStringBean bean) {
                            ToastUtils.showLong(R.string.dev_device_connect_network_success);
                            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.DEV_COUNT_CHANGE,Integer.class).postValue(1);
                            setPageState(0);
                            isRadarConnectNetSuccess.setValue(true);
                        }
                    });
        }
    }

    //在服务器获取雷达状态
    private void getRadarNetWorkStatus(){
        RadarNetworkBean bean = new RadarNetworkBean(radarId);
        httpDisposable = EasyHttp.post(UrlApi.URL.GetRadarNetworkStatus.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(bean))
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(String bean) {
                        if ("true".equals(bean)){
                            setRadarInfo();
                            isStop = true;
                            statusDisposable.dispose();
                        }
                    }
                });
    }


    @Override
    public void onLoad() {

    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (statusDisposable != null){
            statusDisposable.dispose();
        }
        if (httpDisposable != null){
            httpDisposable.dispose();
        }
    }
}
